package org.supper.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.supper.auth.feign.AuthServiceFeign;
import org.supper.auth.entity.Auth;
import org.supper.auth.entity.UserEntity;
import org.supper.auth.dao.LoginMapper;
import org.supper.auth.entity.JWT;
import org.supper.auth.service.LoginService;

import javax.annotation.Resource;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, UserEntity> implements LoginService {

    /**
     * withClient和secret的base64编码
     */
    private static final String ServerAuthorization = "Basic c3VwcGVyOjEyMzQ1Ng==";
    @Resource
    private AuthServiceFeign authServiceFeign;
    @Override
    public Auth login(String userName, String password) {
        JWT jwt = authServiceFeign.getToken(ServerAuthorization,
                "password", userName, password);
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getUsername,userName);
        queryWrapper.eq(UserEntity::getDataActive,1);
        UserEntity user = this.getOne(queryWrapper); Auth auth = new Auth();
        auth.setId(user.getId());
        auth.setHandeUrl(user.getHandeUrl());
        auth.setUsername(user.getUsername());
        auth.setAccessToken(jwt.getAccess_token());
        auth.setJti(jwt.getJti());
        auth.setTokenType(jwt.getToken_type());
        auth.setRefreshToken(jwt.getRefresh_token());
        auth.setExpiresIn(jwt.getExpires_in());
        return auth;
    }

    @Override
    public Auth phoneLogin(String phone, String code) {
        JWT jwt = authServiceFeign.getTokenByPhone(ServerAuthorization,
                "sms_code", phone, code);
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getUsername,phone);
        queryWrapper.eq(UserEntity::getDataActive,1);
        UserEntity user = this.getOne(queryWrapper); Auth auth = new Auth();
        auth.setId(user.getId());
        auth.setHandeUrl(user.getHandeUrl());
        auth.setUsername(user.getUsername());
        auth.setAccessToken(jwt.getAccess_token());
        auth.setJti(jwt.getJti());
        auth.setTokenType(jwt.getToken_type());
        auth.setRefreshToken(jwt.getRefresh_token());
        auth.setExpiresIn(jwt.getExpires_in());
        return auth;
    }
}
